<?php

namespace App\Http\Controllers\Web;

use App\Models\Card;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CardController extends Controller
{
    public function createCard(Request $request)
    {

        //面额
        if ($request->amount < 0 || !is_numeric($request->amount)) {
            return "<script language=javascript>alert('面额格式错误！');history.back();</script>";
        }
        //卡号前缀
        $prefix = $request->prefix;
        if($request->card_length-strlen($prefix)< 4){
            return "<script language=javascript>alert('卡号长度和前缀长度差不能少于4位！');history.back();</script>";
        }
        //卡号长度
        if($request->card_length<8) {
            return "<script language=javascript>alert('卡号不能少于8位！');history.back();</script>";
        }
        //密码长度
        if($request->password<6) {
            return "<script language=javascript>alert('密码不能少于6位！');history.back();</script>";
        }
        //有效期
        if($request->overtime<time()) {
            return "<script language=javascript>alert('过期时间必须在当前时间之后！');history.back();</script>";
        }
        $overtime = date('Y-m-d H:i:s', $request->overtime);
        //卡号长度-前缀
        $rand_length = $request->card_length-strlen($prefix);
        $t = 0;
        //卡号组成
        switch ($request->form){
            //纯数字
            case '0';
                $str='0123456789';
                break;
            //数字加字母
            case '1';
                $str='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                break;
            //数字加小写字母
            case '2';
                $str='abcdefghijklmnopqrstuvwxyz0123456789';
                break;
            //数字加大写字母
            case '3';
                $str='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
                break;
            default;
                $str='0123456789';
                break;

        }
        $len = strlen($str)-1;
        $password_str = '0123456789';
        for($i = 0; $i < $request->num; $i++) {
            $number = $prefix;
            //卡号
            for($x=0;$x<$rand_length;$x++){
                $num = mt_rand(0,$len);
                $number .= $str[$num];
            }
            //密码
            $password = '';
            for($z=0;$z<$request->password;$z++){
                $num = mt_rand(0,9);
                $password .= $password_str[$num];
            }
            if(Card::where('number',$number)->first()) {
                $i--;
            } else {
                $t++;
                $password = mt_rand(100000, '999999');
                $array = [
                    'number'=>$number,
                    'password'=>$password,
                    'amount'=>$request->amount,
                    'editor'=>'admin',
                    'over_time'=>$overtime
                ];
                Card::create($array);
            }
        }
    }
}
